﻿// 重写jquery post/get
jQuery(function () {
    // 重写post
    $.post = function (url, data, success, async, error) {
        var options = {
            url: url,
            data: data,
            async: async,
            type: 'post',
            success: success,
            error: error
        };
        $.plusajax(options);
    };
    // 重写get
    $.get = function (url, data, success, async, error) {
        var options = {
            url: url,
            data: data,
            type: 'get',
            async: async,
            success: success,
            error: error
        };
        $.plusajax(options);
    };
    // 执行ajax
    $.plusajax = function (options) {
        let loading = layer.load(2);
        $.ajax({
            url: options.url,
            data: options.data,
            cache: false,
            async: options.async == undefined ? true : options.async,
            type: options.type,
            dataType: 'json',
            success: function (result) {
                layer.close(loading);
                try {
                    if (typeof (result) == "string") {
                        result = JSON.parse(result);
                    }
                } catch (e) {
                    layer.alert(e);
                    return;
                }
                if (result.succ != undefined && result.succ === false) {
                    if (result.code == "0003") {
                        loginOutTime();
                        return;
                    }
                    else {
                        layer.alert(result.msg);
                        return;
                    }
                } else {
                    options.success(result);
                }
            },
            error: function (a, b, c) {
                layer.close(loading);
                console.log(a);
                console.log(b);
                console.log(c);
                layer.alert('服务器出现错误');
                return;
            }
        });
    };
    // form操作
    $.extend($.fn, {
        getForm: function () {
            var serializeObj = {};
            var array = this.serializeArray();
            var str = this.serialize();
            $(array).each(function () {
                if (serializeObj[this.name]) {
                    if ($.isArray(serializeObj[this.name])) {
                        serializeObj[this.name].push(this.value);
                    } else {
                        serializeObj[this.name] = [serializeObj[this.name], this.value];
                    }
                } else {
                    serializeObj[this.name] = this.value;
                }
            });
            return serializeObj;
        },
        setForm: function (data) {
            return this.each(function () {
                var input, name;
                if (data == null) { this.reset(); return; }
                for (var i = 0; i < this.length; i++) {
                    input = this.elements[i];
                    //checkbox的name可能是name[]数组形式
                    name = (input.type == "checkbox") ? input.name.replace(/(.+)\[\]$/, "$1") : input.name;
                    //if (data[name] == undefined) continue;
                    switch (input.type) {
                        case "checkbox":
                            if (data[name] == "") {
                                input.checked = false;
                            } else {
                                if (data[name].toString().indexOf(input.value) > -1) {
                                    input.checked = true;
                                } else {
                                    input.checked = false;
                                }
                            }
                            break;
                        case "radio":
                            if ($('input:radio[name=' + name + '][value=' + data[name] + ']').length > 0)
                                $('input:radio[name=' + name + '][value=' + data[name] + ']')[0].checked = true;
                            break;
                        case "button": break;
                        case "select-one" || "select":
                            jQuery(input).val(data[name]);
                            break;
                        default:
                            input.value = data[name] == null ? '' : data[name];
                            if ($(input).attr('data-date-format')) {
                                var formart = $(input).attr('data-date-format');
                                formart = formart.replace('yyyy-mm-dd', 'YYYY-MM-DD');
                                input.value = moment(input.value).format(formart);
                            }
                    }
                }

            });
        },
        clearForm: function () {
            try {
                this.reset();
            } catch (e) {
                layer.alert(e.message);
            }
            $(':input', this).each(function () {
                var type = this.type;
                var tag = this.tagName.toLowerCase();
                if (type == 'checkbox' || type == 'radio')
                    this.checked = false;
                else if (tag == 'select')
                    this.selectedIndex = -1;
                else
                    this.value = "";
            });
        }
    });
});
// 登录过期方法
function loginOutTime() {
    layer.confirm('登录失效，请重新登录？', {
        closeBtn: 0,
        btn: ['确定']
    }, function () {
        window.parent.parent.location = '/login/index';
    });
};
// Cookie操作
(function (global) {
    // 获取cookie对象，以对象表示
    function getCookiesObj() {
        var cookies = {};
        if (document.cookie) {
            var objs = document.cookie.split('; ');
            for (var i in objs) {
                var index = objs[i].indexOf('='),
                    name = objs[i].substr(0, index),
                    value = objs[i].substr(index + 1, objs[i].length);
                cookies[name] = value;
                if (i == objs.length - 1) break;
            }
        }
        return cookies;
    }
    // 设置cookie
    function set(name, value, opts) {
        // opts: maxAge, path, domain, secure
        if (name && value) {
            var cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
            // 可选参数
            if (opts) {
                if (opts.maxAge) {
                    cookie += '; max-age=' + opts.maxAge;
                }
                if (opts.path) {
                    cookie += '; path=' + opts.path;
                }
                if (opts.domain) {
                    cookie += '; domain=' + opts.domain;
                }
                if (opts.secure) {
                    cookie += '; secure';
                }
            }
            document.cookie = cookie;
            return cookie;
        } else {
            return '';
        }
    }
    // 获取cookie
    function get(name) {
        return decodeURIComponent(getCookiesObj()[name]) || null;
    }
    // 清除某个cookie
    function remove(name) {
        if (getCookiesObj()[name]) {
            document.cookie = name + '=; max-age=0';
        }
    }
    // 清除所有cookie
    function clear() {
        var cookies = getCookiesObj();
        for (var key in cookies) {
            document.cookie = key + '=; max-age=0';
        }
    }
    // 获取所有cookies
    function getCookies(name) {
        return getCookiesObj();
    }
    // 解决冲突
    function noConflict(name) {
        if (name && typeof name === 'string') {
            if (name && window['cookie']) {
                window[name] = window['cookie'];
                delete window['cookie'];
                return window[name];
            }
        } else {
            return window['cookie'];
            delete window['cookie'];
        }
    }
    global['cookie'] = {
        'gets': getCookies,
        'set': set,
        'get': get,
        'remove': remove,
        'clear': clear,
        'noConflict': noConflict
    };
})(window);
// 日期时间计算
var planDate = function () {
    // 替换字符串 
    function Replace(str, from, to) {
        return str.split(from).join(to);
    }
    // js日期字符串转换成日期类型
    function parseDate(dateStr) {
        return new Date(Replace(dateStr, "-", "/"));
    }
    // 增加月
    function addMonths(date, value) {
        date.setMonth(parseInt(date.getMonth()) + value);
        return date;
    }
    // 增加天  
    function addDays(date, value) {
        date.setDate(parseInt(date.getDate()) + value);
        return date;
    }
    // 增加时
    function addHours(date, value) {
        date.setHours(parseInt(date.getHours()) + value);
        return date;
    }
    // 增加分
    function addMinutes(date, value) {
        date.setMinutes(parseInt(date.getMinutes()) + value);
        return date;
    }
    // 返回月份(两位数)  
    function getFullMonth(date) {
        var v = parseInt(date.getMonth()) + 1;
        if (v > 9) return v.toString();
        return "0" + v;
    }
    // 返回日(两位数)  
    function getFullDate(date) {
        var v = date.getDate();
        if (v > 9) return v.toString();
        return "0" + v;
    }
    // 返回时(两位数)
    function getFullHour(date) {
        var v = date.getHours();
        if (v > 9) return v.toString();
        return "0" + v;
    }
    // 返回分(两位数)
    function getFullMinutes(date) {
        var v = date.getMinutes();
        if (v > 9) return v.toString();
        return "0" + v;
    }
    // 计算相差天数
    function planDays(date1, date2) {
        var date3 = date2.getTime() - date1.getTime()
        var days = Math.floor(date3 / (24 * 3600 * 1000))
        return days;
    }
    // 计算相差小时
    function planHours(date1, date2) {
        var date3 = date2.getTime() - date1.getTime()
        var hours = Math.floor(date3 / (3600 * 1000))
        return hours;
    }
    // 计算相差分钟数
    function planMinutes(date1, date2) {
        var date3 = date2.getTime() - date1.getTime()
        var minutes = Math.floor(date3 / (60 * 1000))
        return minutes;
    }
    // 比较两个时间
    function compareDate(date1, date2) {
        var d1 = parseDate(date1);
        var d2 = parseDate(date2);
        if (d1.getTime() > d2.getTime())
            return true;
        else
            return false;
    }
    return {
        Replace: Replace,
        parseDate: parseDate,
        addMinutes: addMinutes,
        addDays: addDays,
        addHours: addHours,
        getFullMonth: getFullMonth,
        getFullDate: getFullDate,
        getFullHour: getFullHour,
        getFullMinutes: getFullMinutes,
        planDays: planDays,
        planHours: planHours,
        planMinutes: planMinutes,
        compareDate: compareDate
    }
}();
// 格式化日期
Date.prototype.format = function (fmt) { // author: meizz
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
// 删除数组中的某一个元素
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
// 获取地址栏参数
window.request = function (val) {
    var out = "";
    var reg = new RegExp("(^|&)" + val + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) { out = unescape(r[2]); }
    return out;
};
// 验证手机号码
String.prototype.verifyPhone = function () {
    if (!(/^1\d{10}$/.test(this))) {
        return false;
    } else {
        return true;
    }
};
// 验证邮箱地址
String.prototype.verifyPhone = function () {
    if (!(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(this))) {
        return false;
    } else {
        return true;
    }
};
// 获取小数点后长度
String.prototype.decLength = function () {
    var number = this;
    var this_arr = number.toString().split('.');
    return this_arr.length > 1 ? this_arr[1].length : 0;
};
// 截取指定长度字符串
String.prototype.subLast = function (length, laststr) {
    var str = this.toString();
    if (str) {
        if (!length) {
            length = 10;
        }
        if (!laststr) {
            laststr = '...';
        }
        if (str.length > length) {
            return str.substr(0, length) + laststr;
        } else {
            return str;
        }
    } else {
        return '';
    }
    var this_arr = number.toString().split('.');
    return this_arr.length > 1 ? this_arr[1].length : 0;
};
// iframe-container
(function (global) {
    // 打开/切换一个窗口
    function open(funcid, url, title) {
        var iframeArray = $('#iframe-container').find('iframe');
        var itemArray = $('#iframe-item-container').find('li');
        if (iframeArray.length <= 10) {
            var isHave = false;
            for (var item of itemArray) {
                if ($(item).data('funcid') == funcid) {
                    $(item).addClass('layui-this');
                    isHave = true;
                } else {
                    $(item).removeClass('layui-this');
                }
            }
            for (var item of iframeArray) {
                if ($(item).data('funcid') == funcid) {
                    $(item).show();
                } else {
                    $(item).hide();
                }
            }
            if (!isHave) {
                var _item = '<li class="layui-nav-item layui-this" data-funcid="' + funcid + '"><a href="javascript:void(0);" data-funcid="' + funcid + '"  onclick="javascript: { iframe.open(\'' + funcid + '\',\'' + url + '\',\'' + title + '\'); }" >' + title + '<i class="layui-icon iframe-close" onclick="javascript:{ iframe.close(\'' + funcid + '\',event); }">&#x1006;</i></a></li>';
                var _iframe = '<iframe class="iframe-option" src="' + url + '" data-funcid="' + funcid + '"></iframe>';
                $('#iframe-item-container').append(_item);
                $('#iframe-container').append(_iframe);
            }
        } else {
            layer.alert('不能再打开新的标签页了<br>请关闭一部分标签页后在尝试');
        }
    };
    // 关闭一个窗口
    function close(funcid, event) {
        var iframeArray = $('#iframe-container').find('iframe');
        var itemArray = $('#iframe-item-container').find('li');
        var isPage = false;
        for (var item of iframeArray) {
            if ($(item).data('funcid') == funcid) {
                $(item).remove();
                break;
            }
        }
        for (var item of itemArray) {
            if ($(item).data('funcid') == funcid) {
                if ($(item).hasClass('layui-this')) {
                    isPage = true;
                }
                $(item).remove();
                break;
            }
        }
        event.stopPropagation();
        if (isPage) {
            iframe.open('homePage', '', '首页');
        }
    };
    // 关闭全部窗口
    function closeAll(event) {
        var iframeArray = $('#iframe-container').find('iframe');
        var itemArray = $('#iframe-item-container').find('li');
        var isPage = false;
        for (var item of iframeArray) {
            if ($(item).data('funcid') != 'homePage') {
                $(item).remove();
            }
        }
        for (var item of itemArray) {
            if ($(item).data('funcid') != 'homePage') {
                $(item).remove();
            }
        }
        iframe.open('homePage', '', '首页');
    };
    global['iframe'] = {
        'open': open,
        'close': close,
        'closeAll': closeAll
    };
})(window);